﻿$(function () {
	$('.portlet')
		.sortable({
			connectWith: '.column',
			opacity: '0.5',
			pullPlaceholder: true,
			disabled: true,
			stop: function (event, ui) {
				var itemId = ui.item[0].id;
				var parentId = ui.item[0].parentNode.id;

				$.ajax({
					url: document.location.origin + '/Dynamic/AtualizarLocalizacao',
					type: 'post',
					dataType: 'json',
					data: {
						Url: document.URL,
						Localizacao: JSON.stringify(getJSONPortlets())
					},
					success: function (data) {
						window.location = data.url;
					},
					error: function (data) {

					}
				});

				$(this).sortable('refresh');
			}
		})
		.disableSelection();
});

function getJSONPortlets() {
	var portlets = $('#portlet_container').find('.portlet');
	var webparts = [];
	var localizacao = [];

	for (var x = 0; x < portlets.length; x++) {
		webparts = $('#' + portlets[x].id).sortable('toArray');

		for (var y = 0; y < webparts.length; y++) {
			localizacao.push({
				"Id": webparts[y].split('-')[1].toString(),
				"Linha": portlets[x].id.split('-')[1].toString(),
				"Coluna": portlets[x].id.split('-')[2].toString(),
				"Ordem": y.toString()
			});
		}
	}

	return localizacao;
}
